<?php
class Validate_StringEquals extends Zend_Validate_Abstract
{

	const NOT_EQUAL = 'stringNotEqual';
	const MISSING = 'stringMissing';

	protected $_messageTemplates = array(
		self::NOT_EQUAL => "%field1% and %field2% are not equal.",
		self::MISSING => "One or both strings are missing."
	);

	/**
     * @var array
     */
    protected $_messageVariables = array(
        'field1' => '_field1',
    	'field2' => '_field2',
    );
	
	protected $_field1 = null;
	protected $_field2 = null;
 	protected $_encoding = null;
	
	/**
	  * Sets validator options
	  *
	  * @param string|array $options
	  * @return void
	  */
	public function __construct($options = array()) {

		if (array_key_exists('encoding', $options)) {
            $this->setEncoding($options['encoding']);
        }
	}
	
	/**
     * Returns the actual encoding
     *
     * @return string
     */
    public function getEncoding()
    {
        return $this->_encoding;
    }

    /**
     * Sets a new encoding to use
     *
     * @param string $encoding
     * @return Zend_Validate_StringLength
     */
    public function setEncoding($encoding = null)
    {
        if ($encoding !== null) {
            $orig   = iconv_get_encoding('internal_encoding');
            $result = iconv_set_encoding('internal_encoding', $encoding);
            if (!$result) {
                require_once 'Zend/Validate/Exception.php';
                throw new Zend_Validate_Exception('Given encoding not supported on this OS!');
            }

            iconv_set_encoding('internal_encoding', $orig);
        }

        $this->_encoding = $encoding;
        return $this;
    }
	
	
	 /**
	  * Defined by Zend_Validate_Interface
	  *
	  * Returns true if and only if the the 2 strings are equal
	  *
	  * @param array $value
	  * @return boolean
	  */
	public function isValid($value) {
	
		if (!is_array($value) && count($value) < 2) {
            $this->_error(self::MISSING);
            return false;
        }

        $this->_field1 = array_shift($value);
        $this->_field2 = array_shift($value);
        
        if ($this->_field1 != $this->_field2) {
        	$this->_error(self::NOT_EQUAL);
        }
        
        if (count($this->_messages)) {
            return false;
        } else {
            return true;
        }
	}
}